import axios from 'axios';
import { ElMessage } from 'element-plus'

const instance = axios.create({
    // 使用相对路径，让代理处理
    baseURL: '/api',
    timeout: 30000,
});

// 添加响应拦截器处理超时
instance.interceptors.response.use(
    response => response,
    error => {
        if (error.code === 'ECONNABORTED') {
            ElMessage.error('请求超时，请稍后重试')
        }
        return Promise.reject(error)
    }
)

instance.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

instance.interceptors.response.use(
    response => {
        return response.data
    },
    error => {
        console.error('请求错误:', error.response?.data || error.message)
        ElMessage.error(error.response?.data?.message || '请求失败')
        return Promise.reject(error)
    }
)

export default instance;